import { h } from "snabbdom/build/h";
import { init } from "snabbdom/build/init";
// 下面内容请按需导入
import { classModule } from "snabbdom/build/modules/class";
import { propsModule } from "snabbdom/build/modules/props.js";
import { styleModule } from "snabbdom/build/modules/style.js";
import { eventListenersModule } from "snabbdom/build/modules/eventlisteners.js";

const patch = init([
  classModule,
  propsModule,
  styleModule,
  eventListenersModule,
]);

const data = [];

const getRandomData = (() => {
  let len = data.length;
  // 获取随机字符串
  function getRandomdStr(num = 5) {
    var possible =
      "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    let text = "";
    for (let i = 0; i < num; i++)
      text += possible.charAt(Math.floor(Math.random() * possible.length));
    return text;
  }
  return function () {
    return {
      id: ++len,
      name: getRandomdStr(5),
      desc: getRandomdStr(16),
    };
  };
})();

const handleForSort = (key) => {
  return {
    props: { href: "#" },
    style: { fontSize: "20px", marginLeft: "10px" },
    on: {
      click: () => {
        if (key === "id") {
          data.sort((a, b) => a["id"] - b["id"]);
        } else {
          data.sort((a, b) => a[key].localeCompare(b[key]));
        }
        oldVnode = patch(oldVnode, viewList(data));
      },
    },
  };
};

const handleAdd = () => {
  return {
    props: { href: "#" },
    style: { marginLeft: "220px", fontSize: "20px" },
    on: {
      click: () => {
        data.unshift(getRandomData());
        oldVnode = patch(oldVnode, viewList(data));
      },
    },
  };
};

for (let i = 0; i < 10; i++) {
  data.push(getRandomData());
}
let root = document.querySelector("#root");

// 创建列表
const viewList = (data) => {
  const title = h("h1#container", "TOP 10 Movice");
  const tool = h("div", { style: { marginBottom: "10px" } }, [
    h("span", "Sort by"),
    h("a.sortbtn", handleForSort("id"), "排名"),
    h("a.sortbtn", handleForSort("name"), "名称"),
    h("a.add", handleAdd(), "新增"),
  ]);
  const tableHeader = h("tr", [
    h("th", { style: { width: "100px" } }, "排名"),
    h("th", { style: { width: "100px" } }, "名称"),
    h("th", { style: { width: "200px" } }, "描述"),
  ]);
  const tableList = data.map((item) => {
    return h("tr", [h("td", item.id), h("td", item.name), h("td", item.desc)]);
  });
  return h("div.container", [
    title,
    tool,
    h("table", { props: { border: "1px" } }, [tableHeader, ...tableList]),
  ]);
};

let oldVnode = patch(root, viewList(data));
